import {
  createEntityAdapter,
  createSlice,
  nanoid,
  PayloadAction,
} from "@reduxjs/toolkit";
import { AppState } from "@store/index";

export interface HistoryType {
  name: string;
  id: string;
}

const historyEntityAdaptor = createEntityAdapter<HistoryType>();

export const historySlice = createSlice({
  name: "history",
  initialState: historyEntityAdaptor.getInitialState(),
  reducers: {
    // 添加一条历史记录
    addHistory: {
      reducer(state, action: PayloadAction<HistoryType>) {
        historyEntityAdaptor.addOne(state, action);
      },
      prepare(payload) {
        return {
          payload: { ...payload, id: nanoid() },
        };
      },
    },
    // 删除一条历史记录
    removeHistory(state, action: PayloadAction<string>) {
      historyEntityAdaptor.removeOne(state, action);
    },
    // 清空历史记录
    clearHistory(state) {
      historyEntityAdaptor.removeAll(state);
    },
  },
});

export const historySelector = historyEntityAdaptor.getSelectors<AppState>(
  (state) => state.history
);

export const { addHistory, removeHistory, clearHistory } = historySlice.actions;
